<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="模板名称关键词"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-select v-model="queryParams.templateType" placeholder="选择类型" clearable style="width: 120px">
          <el-option label="日报" value="daily"></el-option>
          <el-option label="周报" value="weekly"></el-option>
          <el-option label="月报" value="monthly"></el-option>
          <el-option label="自定义" value="custom"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报表类别" prop="reportCategory">
        <el-select v-model="queryParams.reportCategory" placeholder="选择类别" clearable style="width: 140px">
          <el-option label="设备统计" value="device"></el-option>
          <el-option label="环境监测" value="environment"></el-option>
          <el-option label="检测分析" value="detection"></el-option>
          <el-option label="告警统计" value="alarm"></el-option>
          <el-option label="综合概览" value="overview"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="状态" clearable style="width: 100px">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:reportTemplate:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:reportTemplate:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reportTemplate:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:reportTemplate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="reportTemplateList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="templateId" width="80" />
      <el-table-column label="模板名称" align="center" prop="templateName" min-width="180" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="templateType" width="90">
        <template slot-scope="scope">
          <el-tag :type="getTypeTagType(scope.row.templateType)" size="mini">
            {{ getTypeLabel(scope.row.templateType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报表类别" align="center" prop="reportCategory" width="100">
        <template slot-scope="scope">
          <el-tag :type="getCategoryTagType(scope.row.reportCategory)" size="mini">
            {{ getCategoryLabel(scope.row.reportCategory) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="数据源" align="center" prop="dataSources" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.dataSources" style="font-size: 12px; color: #606266;">
            {{ formatJsonSummary(scope.row.dataSources) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="图表配置" align="center" prop="chartConfig" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.chartConfig" style="font-size: 12px; color: #606266;">
            {{ formatJsonSummary(scope.row.chartConfig) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="生成计划" align="center" prop="generationSchedule" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.generationSchedule" style="font-size: 12px; font-family: monospace;">
            {{ scope.row.generationSchedule }}
          </span>
          <span v-else style="color: #909399;">手动生成</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="isActive" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActive"
            active-value="1"
            inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            @change="handleStatusChange(scope.row)"
            :disabled="!hasPermission(['system:reportTemplate:edit'])"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span style="font-size: 12px;">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            style="color: #409eff;"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reportTemplate:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reportTemplate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报表模板配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <el-divider content-position="left">基本信息</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="报表模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="templateType">
              <el-select v-model="form.templateType" placeholder="选择模板类型" style="width: 100%">
                <el-option label="日报" value="daily">
                  <span style="float: left">日报</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">每日生成</span>
                </el-option>
                <el-option label="周报" value="weekly">
                  <span style="float: left">周报</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">每周生成</span>
                </el-option>
                <el-option label="月报" value="monthly">
                  <span style="float: left">月报</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">每月生成</span>
                </el-option>
                <el-option label="自定义" value="custom">
                  <span style="float: left">自定义</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">按需生成</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报表类别" prop="reportCategory">
              <el-select v-model="form.reportCategory" placeholder="选择报表类别" style="width: 100%">
                <el-option label="设备统计" value="device">
                  <i class="el-icon-cpu"></i> 设备统计
                </el-option>
                <el-option label="环境监测" value="environment">
                  <i class="el-icon-sunny"></i> 环境监测
                </el-option>
                <el-option label="检测分析" value="detection">
                  <i class="el-icon-search"></i> 检测分析
                </el-option>
                <el-option label="告警统计" value="alarm">
                  <i class="el-icon-warning"></i> 告警统计
                </el-option>
                <el-option label="综合概览" value="overview">
                  <i class="el-icon-pie-chart"></i> 综合概览
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isActive">
              <el-switch
                v-model="form.isActive"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <el-tooltip content="启用后模板可用于生成报表" placement="right">
                <i class="el-icon-question" style="margin-left: 8px; color: #909399;"></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
          
          <!-- 配置信息 -->
          <el-col :span="24">
            <el-divider content-position="left">配置信息</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源配置" prop="dataSources">
              <el-input 
                v-model="form.dataSources" 
                type="textarea" 
                :rows="4"
                placeholder='{"tables": ["device_info"], "date_range": "yesterday"}'
                style="font-family: monospace; font-size: 12px;"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                JSON格式，配置数据表和时间范围
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图表配置" prop="chartConfig">
              <el-input 
                v-model="form.chartConfig" 
                type="textarea" 
                :rows="4"
                placeholder='{"charts": [{"type": "line", "title": "趋势图"}]}'
                style="font-family: monospace; font-size: 12px;"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                JSON格式，配置图表类型和样式
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板内容" prop="templateContent">
              <el-input 
                v-model="form.templateContent" 
                type="textarea" 
                :rows="6"
                placeholder="HTML模板内容或JSON配置"
                style="font-family: monospace; font-size: 12px;"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                支持HTML模板或JSON配置格式
              </div>
            </el-form-item>
          </el-col>
          
          <!-- 自动化配置 -->
          <el-col :span="24">
            <el-divider content-position="left">自动化配置</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成计划" prop="generationSchedule">
              <el-input 
                v-model="form.generationSchedule" 
                placeholder="0 8 * * *"
                style="font-family: monospace;"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                Cron表达式，如：0 8 * * *（每天8点）
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自动发送配置" prop="autoSendConfig">
              <el-input 
                v-model="form.autoSendConfig" 
                type="textarea" 
                :rows="3"
                placeholder='{"emails": ["admin@example.com"]}'
                style="font-family: monospace; font-size: 12px;"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 5px;">
                JSON格式，配置邮件接收人等
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReportTemplate, getReportTemplate, delReportTemplate, addReportTemplate, updateReportTemplate } from "@/api/system/reportTemplate";

export default {
  name: "ReportTemplate",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表模板配置表格数据
      reportTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        templateType: null,
        reportCategory: null,
        dataSources: null,
        chartConfig: null,
        templateContent: null,
        generationSchedule: null,
        autoSendConfig: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        templateType: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
        reportCategory: [
          { required: true, message: "报表类别不能为空", trigger: "change" }
        ],
        dataSources: [
          { required: true, message: "数据源配置(JSON格式)不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报表模板配置列表 */
    getList() {
      this.loading = true;
      listReportTemplate(this.queryParams).then(response => {
        this.reportTemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        templateType: null,
        reportCategory: null,
        dataSources: null,
        chartConfig: null,
        templateContent: null,
        generationSchedule: null,
        autoSendConfig: null,
        isActive: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报表模板配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids
      getReportTemplate(templateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报表模板配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.templateId != null) {
            updateReportTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReportTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除报表模板配置编号为"' + templateIds + '"的数据项？').then(function() {
        return delReportTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/reportTemplate/export', {
        ...this.queryParams
      }, `reportTemplate_${new Date().getTime()}.xlsx`)
    },
    /** 获取模板类型标签样式 */
    getTypeTagType(type) {
      const typeMap = {
        'daily': 'primary',
        'weekly': 'success',
        'monthly': 'warning',
        'custom': 'info'
      };
      return typeMap[type] || '';
    },
    /** 获取模板类型显示标签 */
    getTypeLabel(type) {
      const labelMap = {
        'daily': '日报',
        'weekly': '周报',
        'monthly': '月报',
        'custom': '自定义'
      };
      return labelMap[type] || type;
    },
    /** 获取报表类别标签样式 */
    getCategoryTagType(category) {
      const typeMap = {
        'device': 'primary',
        'environment': 'success',
        'detection': 'warning',
        'alarm': 'danger',
        'overview': 'info'
      };
      return typeMap[category] || '';
    },
    /** 获取报表类别显示标签 */
    getCategoryLabel(category) {
      const labelMap = {
        'device': '设备统计',
        'environment': '环境监测',
        'detection': '检测分析',
        'alarm': '告警统计',
        'overview': '综合概览'
      };
      return labelMap[category] || category;
    },
    /** 格式化JSON摘要显示 */
    formatJsonSummary(jsonStr) {
      if (!jsonStr) return '-';
      try {
        const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr;
        const keys = Object.keys(obj);
        if (keys.length <= 2) {
          return keys.join(', ');
        } else {
          return `${keys.slice(0, 2).join(', ')}... (+${keys.length - 2})`;
        }
      } catch (e) {
        return jsonStr.length > 20 ? jsonStr.substring(0, 20) + '...' : jsonStr;
      }
    },
    /** 状态变更处理 */
    handleStatusChange(row) {
      const text = row.isActive === '1' ? '启用' : '禁用';
      this.$modal.confirm(`确认要${text}模板"${row.templateName}"吗？`).then(() => {
        return updateReportTemplate(row);
      }).then(() => {
        this.$modal.msgSuccess(`${text}成功`);
        this.getList();
      }).catch(() => {
        // 还原状态
        row.isActive = row.isActive === '1' ? '0' : '1';
      });
    },
    /** 预览模板 */
    handlePreview(row) {
      this.$modal.msgInfo('预览功能开发中...', '提示');
      // TODO: 实现模板预览功能
    },
    /** 权限检查 */
    hasPermission(permissions) {
      // 简单实现，实际项目中应该调用权限检查方法
      return true;
    }
  }
};
</script>

<style scoped>
/* 优化表格样式 */
.common-table {
  font-size: 13px;
}

.common-table .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 优化数值显示 */
.common-table .el-table__cell {
  padding: 8px 0;
}

/* 标签样式 */
.el-tag {
  font-weight: 500;
}

/* 开关样式 */
.el-switch {
  transform: scale(0.9);
}

/* 表单优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-divider {
  margin: 15px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

/* 搜索表单优化 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 下拉框选项样式 */
.el-select-dropdown__item {
  padding: 8px 20px;
}

.el-select-dropdown__item i {
  margin-right: 8px;
  color: #409eff;
}

/* JSON配置文本框样式 */
.el-textarea__inner {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
}

/* 提示文字样式 */
.help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 工具提示图标 */
.help-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
}

.help-icon:hover {
  color: #409eff;
}

/* 操作按钮优化 */
.el-button--text {
  padding: 2px 4px;
  margin: 0 2px;
}

/* 预览按钮特殊样式 */
.preview-btn {
  color: #409eff !important;
  font-weight: 500;
}

.preview-btn:hover {
  color: #66b1ff !important;
}

/* JSON摘要显示 */
.json-summary {
  font-family: monospace;
  font-size: 11px;
  color: #606266;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Cron表达式样式 */
.cron-expression {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  background-color: #f5f7fa;
  padding: 2px 4px;
  border-radius: 3px;
}

/* 状态开关禁用样式 */
.el-switch.is-disabled {
  opacity: 0.6;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 20px;
}

.form-section .el-divider {
  margin: 20px 0 15px 0;
}

/* 配置文本框样式增强 */
.config-textarea .el-textarea__inner {
  background-color: #fafafa;
  border: 1px dashed #d9d9d9;
}

.config-textarea .el-textarea__inner:focus {
  border-color: #409eff;
  background-color: #fff;
}
</style>
